using PolygonTool;
using System.Collections.Generic;
using UnityEngine;

public class PolygonMesh : MonoBehaviour
{
    GameObject mg;
    MeshFilter mf;
    MeshRenderer mr;
    Mesh m;

    Camera mainCam;
    public Material mat;
    public List<Vector3> posList = new List<Vector3>();
    Triangulation triangulation;
    List<int> resultList = new List<int>();

    // Start is called before the first frame update
    void Start()
    {
        mg = new GameObject("PolygonMesh");
        mf = mg.AddComponent<MeshFilter>();
        mr = mg.AddComponent<MeshRenderer>();
        mr.material = mat;
        m = new Mesh();

        mainCam = Camera.main;
    }

    Ray ray;
    RaycastHit hit;
    Vector3 lastPoint;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            ray = mainCam.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                lastPoint = hit.point;
                posList.Add(lastPoint);
                if (posList.Count > 2)
                {
                    CreatMesh();
                }
            }
        }
    }

    void CreatMesh()
    {
        triangulation = new Triangulation(posList);

        triangulation.SetCompareAxle(CompareAxle.Y);

        int[] a = triangulation.GetTriangles();

        if (a != null)
        {
            for (int i = 0; i < a.Length; i++)
            {
                Debug.Log("===:" + a[i]);
                resultList.Add(a[i]);
            }
        }
        else
        {
            Debug.LogError("a == null");
            posList.Remove(lastPoint);
            return;
        }

        Vector3[] vertexs = new Vector3[a.Length];

        for (int i = 0; i < vertexs.Length; i++)
        {
            Vector3 v = posList[a[i]];
            vertexs[i] = v;
        }

        m.vertices = vertexs;

        int[] tri = new int[a.Length];

        for (int i = 0; i < tri.Length; i += 3)
        {
            tri[i] = i;
            tri[i + 1] = i + 2;
            tri[i + 2] = i + 1;
        }
        m.triangles = tri;
        mf.mesh = m;
    }
}